#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name:     plugins.py
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Licence:  GPLv3
# Version:  101216

from google.appengine.api import urlfetch
import re, types, cleverbot, pinyin, time, os

re_fh = re.compile(r'[^a-zA-Z ]+')
re_py = re.compile(r'[a-zA-Z ]+')

class translate():
    def __init__(self):
        self.textre = re.compile("\!\[CDATA\[(.*?)\]\]", re.DOTALL)

    def get_text(self, xml):
        match = re.search(self.textre, xml)
        if not match:
            return xml
        return match.group(1)

    def get_elements(self, xml, elem):
        p = re.compile("<" + elem + ">" + "(.*?)</" + elem + ">", re.DOTALL)
        it = p.finditer(xml)
        result = []
        for m in it:
            result.append(m.group(1))
        return result

    def crawl_xml(self, queryword):
        xml_file = urlfetch.fetch(
                "http://fanyi.youdao.com/translate?doctype=xml&xmlVersion=1.3&i=%s" %
                urlfetch.urllib2.quote(queryword))
        return xml_file.content

    def handle(self, *words):
        if words[0].replace(' ', ''):
            return self.get_text(self.get_elements(self.crawl_xml(words[0]), 'translation')[0])
        else:
            return 'No word to translate!'

def py2hz_repl(x):
    return pinyin.py2hz(x.group(0).replace(' ', '').lower())

class chat():
    def __init__(self):
        self.mycb = cleverbot.Session()
        self.p = pinyin.Pinyin()

    def handle(self, *words):
        if words[0].replace(' ', ''):
            w = self.p.get_pinyin(' '.join(words))
            w = re_fh.sub('', w)
            try:
                time.sleep(1)
                asw = self.mycb.Ask(w)
                if self.p.is_zh:
                    return re_py.sub(py2hz_repl, asw)
                else:
                    return asw
            except:
                    time.sleep(3)
                    return ':)'

class mypinyin():
    def __init__(self):
        pass

    def handle(self, *words):
        if words[0].replace(' ', ''):
            return re_py.sub(py2hz_repl, ' '.join(words))
